package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.adapter.CarAdapter;
import com.rh.bmw4s.bean.BaseBean;
import com.rh.bmw4s.bean.BrandBean;
import com.rh.bmw4s.bean.CarBean;
import com.rh.bmw4s.bean.MyHashMap;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.DealResult;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class TyreActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.title_right_one_btn)
    ImageView titleRightOneBtn;
    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.tv_brand)
    TextView tvBrand;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_choose)
    TextView tvChoose;
    @BindView(R.id.ll_choose)
    LinearLayout llChoose;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    Unbinder unbinder;
    private boolean isPriceUp=false;
    PopupWindow popAll;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private CarAdapter mAdapter;
    private String ids="";
    private String ids1="";
    private int type=0;
    private int page=0;
    private int count=0;
    private int requestNum=10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tyre);
        ButterKnife.bind(this);
        initView();
    }


    private void initView() {
        tvMiddleTitle.setText("汽车轮胎");
        titleRightOneBtn.setVisibility(View.VISIBLE);
        recyclerView.setLayoutManager(new GridLayoutManager(TyreActivity.this,2));
        mAdapter = new CarAdapter(TyreActivity.this);
        mAdapter.setDataList(new ArrayList<CarBean>());
        lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.divider_height_4)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_1)
                .build();
//        recyclerView.addItemDecoration(divider);
        recyclerView.setLoadMoreEnabled(true);
        recyclerView.setPullRefreshEnabled(true);
        recyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mAdapter.clear();
                page=0;
                lRecyclerViewAdapter.notifyDataSetChanged();
                getDatas();
            }
        });
        recyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if(count<(page*requestNum)){
                    ToastUtils.toastForShort(TyreActivity.this,getString(R.string.no_more));
                    recyclerView.setNoMore(true);
                }else{
                    page++;
                    getDatas();

                }
            }
        });
        recyclerView.refresh();
    }
    String carBrand="";
    String carType="";
    String price="";
    String kilo="";
    String year="";
    String pai="";
    String gearbox="";
    String engin="";
    String standard="";
    String carSource="";
    String color="";
    String area="";

    private void getDatas() {
        OkGo.<String>post(Constant.TYRE_LIST)
                .tag(this)
                .params("type", type)
                .params("car_brand", carBrand)
                .params("car_type", carType)
                .params("price", price)
                .params("kilo", kilo)
                .params("year", year)
                .params("pai", pai)
                .params("gearbox", gearbox)
                .params("engin", engin)
                .params("standard", standard)
                .params("car_source", carSource)
                .params("color", color)
                .params("area", area)
                .params("page", page)
                .params("count", requestNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<CarBean> bean = DealResult.getInstace().dealData(TyreActivity.this, response, new TypeToken<BaseBean<CarBean>>() {
                        }.getType());
                        if(bean==null){
                            return;
                        }
                        List<CarBean> beans = bean.getDatas();
                        setDatas(beans);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(TyreActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    private void setDatas(List<CarBean> beans) {
        mAdapter.addAll(beans);
        count=mAdapter.getItemCount();
        recyclerView.refreshComplete(requestNum);
    }



    @OnClick({R.id.title_left_one_btn, R.id.title_right_one_btn, R.id.tv_all, R.id.tv_brand, R.id.tv_price, R.id.tv_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.title_right_one_btn:
                startActivity(new Intent(this,SearchActivity.class));
                break;
            case R.id.tv_all:
                showAllPop();
                break;
            case R.id.tv_brand:
                startActivityForResult(new Intent(TyreActivity.this, CategoryActivity.class),0);
                break;
            case R.id.tv_price:
                if(isPriceUp){
                    isPriceUp=false;
                    mAdapter.clear();
                    lRecyclerViewAdapter.notifyDataSetChanged();
                    type=1;
                    getDatas();

                }else{
                    isPriceUp=true;
                    isPriceUp=false;
                    mAdapter.clear();
                    lRecyclerViewAdapter.notifyDataSetChanged();
                    type=2;
                    getDatas();
                }
                break;
            case R.id.tv_choose:
                startActivityForResult(new Intent(TyreActivity.this, FilterActivity.class),0);
                break;
        }
    }

    private void showAllPop() {
        View contentView = LayoutInflater.from(TyreActivity.this).inflate(R.layout.pop_rank, null);
        popAll = new PopupWindow(TyreActivity.this);
        popAll.setContentView(contentView);
        popAll.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popAll.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popAll.setTouchable(true);
        popAll.setOutsideTouchable(true);
        popAll.showAsDropDown(llChoose);
        contentView.findViewById(R.id.tv_default).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvAll.setText("默认排序");
                popAll.dismiss();
                mAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();
                type=0;
                getDatas();}
        });
//        contentView.findViewById(R.id.tv_price_high).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                tvAll.setText("价格最高");
//                popAll.dismiss();
//                mAdapter.clear();
//                lRecyclerViewAdapter.notifyDataSetChanged();
//                type=1;
//                getDatas();}
//        });
//        contentView.findViewById(R.id.tv_price_low).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                tvAll.setText("价格最低");
//                popAll.dismiss();
//                mAdapter.clear();
//                lRecyclerViewAdapter.notifyDataSetChanged();
//                type=2;
//                getDatas();}
//        });
        contentView.findViewById(R.id.tv_mileage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvAll.setText("里程最短");
                popAll.dismiss();
                mAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();
                type=3;
                getDatas();}
        });
        contentView.findViewById(R.id.tv_year).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tvAll.setText("车龄最短");
                popAll.dismiss();
                mAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();
                type=4;
                getDatas();}
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(popAll!=null){
            popAll.dismiss();
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case Constant.SUCESS_BRAND:
                BrandBean.BrandsBean bean = (BrandBean.BrandsBean) data.getSerializableExtra("bean");
//                tvBrand.setText(bean.getModel_name());
                carBrand = bean.getId()+"";
                getDatas();
                break;
            case Constant.SUCESS_FILTRE:
                carBrand="";
                carType="";
                price="";
                kilo="";
                year="";
                pai="";
                gearbox="";
                engin="";
                standard="";
                carSource="";
                color="";
                area="";
                Bundle bundle = data.getExtras();
                MyHashMap myHashMap= (MyHashMap) bundle.get("maps");
                HashMap<String,String> map=myHashMap.getMap();
                Iterator iterator=map.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry entry = (Map.Entry) iterator.next();
                    String title=entry.getKey().toString();
                    Log.d("CCC","--"+title);
                    if(title.contains("品牌")){
                        carBrand=entry.getValue().toString();
                    }
                    else if(title.contains("车辆级别")){
                        carType=entry.getValue().toString();
                    }else if(title.contains("价格")){
                        price=entry.getValue().toString();
                    }else if(title.contains("里程")){
                        kilo=entry.getValue().toString();
                    }else if(title.contains("年限")){
                        year=entry.getValue().toString();
                    }else if(title.contains("排量")){
                        pai=entry.getValue().toString();
                    }else if(title.contains("变速箱")){
                        gearbox=entry.getValue().toString();
                    }else if(title.contains("发动机")){
                        engin=entry.getValue().toString();
                    }else if(title.contains("排放标准")){
                        standard=entry.getValue().toString();
                    }else if(title.contains("车源")){
                        carSource=entry.getValue().toString();
                    }else if(title.contains("颜色")){
                        color=entry.getValue().toString();
                        if(color.endsWith(",")){
                            color=color.substring(0,color.length()-1);
                        }
                    }
                    else if(title.contains("产地")){
                        area=entry.getValue().toString();
                    }
                }
                getDatas();
                break;
        }
    }
}
